// SearchResultDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TopMost.h"
#include "SearchResultDlg.h"

// CSearchResultDlg dialog

IMPLEMENT_DYNAMIC(CSearchResultDlg, CDialog)

CSearchResultDlg::CSearchResultDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSearchResultDlg::IDD, pParent)
	, m_pEditInMF(NULL)
{

}

CSearchResultDlg::~CSearchResultDlg()
{
}

BOOL CSearchResultDlg::SetCurHwnd(HWND hwnd)
{
	if (hwnd && ::IsWindow(hwnd))
	{
		m_ResultTree.DeleteAllItems();

		Recusion(hwnd, 0);

		m_ResultTree.SetFocus();

		return TRUE;
	}
	return FALSE;
}

BOOL CSearchResultDlg::SetMainDlg(void* pMainDlg)
{
	m_pEditInMF = (CEdit*) pMainDlg;

	return TRUE;
}

HTREEITEM CSearchResultDlg::Recusion(HWND hwnd, INT nLevel)
{
	if (hwnd && ::IsWindow(hwnd))
	{
		HWND hParent = ::GetParent(hwnd);
		HTREEITEM hItemParent = Recusion(hParent, nLevel + 1);

		TCHAR className[256] = {};
		GetClassName(hwnd, className, 256); 
		CString str;
		str.Format(L"%p   %s", hwnd, className);

		HTREEITEM self =  m_ResultTree.InsertItem(str, hItemParent);

		//if ( hItemParent != TVI_ROOT)
		{
			HWND hSibling = ::GetWindow(hwnd, GW_HWNDNEXT);

			while (hSibling)
			{
				//CString str;
				//str.Format(L"%p", hSibling);
				TCHAR className[256] = {};
				GetClassName(hSibling, className, 256); 
				CString str;
				str.Format(L"%p   %s", hSibling, className);

				m_ResultTree.InsertItem(str, hItemParent);
				hSibling = ::GetWindow(hSibling, GW_HWNDNEXT);
			}
		}
		
		//m_ResultTree.Expand(hItemParent, TVE_EXPAND);
		
		if ( nLevel == 0 )
		{
			m_ResultTree.SelectItem(self);
		}
		return self;
	}

	return TVI_ROOT;
}

void CSearchResultDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_TREE1, m_ResultTree);
}


BEGIN_MESSAGE_MAP(CSearchResultDlg, CDialog)
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, &CSearchResultDlg::OnTvnSelchangedTree1)
END_MESSAGE_MAP()


// CSearchResultDlg message handlers

void CSearchResultDlg::OnTvnSelchangedTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
	// TODO: Add your control notification handler code here
	
	if ( m_pEditInMF )
	{
		CString str = m_ResultTree.GetItemText(pNMTreeView->itemNew.hItem);
		m_pEditInMF->SetWindowText(str);
	}

	*pResult = 0;
}

BOOL CSearchResultDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// TODO:  Add extra initialization here
	//ModifyStyleEx(0, WS_EX_NOACTIVATE); 

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
